package com.sljy.hzk.ui.exam;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.renderscript.Sampler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.api.InjectParam;
import com.google.gson.Gson;
import com.sljy.hzk.R;
import com.sljy.hzk.annotation.ActivityInfo;
import com.sljy.hzk.base.BaseActivity;
import com.sljy.hzk.base.UserInfo;
import com.sljy.hzk.entity.ExamErrDetailEntity;
import com.sljy.hzk.entity.ExamInfosEntity;
import com.sljy.hzk.entity.ExamSubjectEntity;
import com.sljy.hzk.entity.UserEntity;
import com.sljy.hzk.net.BaseCallBack;
import com.sljy.hzk.net.HttpHeper;
import com.sljy.hzk.net.service.ExamService;
import com.sljy.hzk.room.AppDataBase;
import com.tkk.api.RxEventProcessor;
import com.tkk.api.annotation.Recipient;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

@ActivityInfo(layout = R.layout.activity_exam_error_record, isShowActionBar = true, title = "错题记录", rightIcRes = R.drawable.homepage)
public class ExamErrorRecordActivity extends BaseActivity {
    @BindView(R.id.recycer)
    RecyclerView recycerView;
    private static final int SPAN_COUNT = 6;
    BaseMultiItemQuickAdapter adapter;
    List<ExamErrDetailEntity.SubjectBean> subjectBeans = new ArrayList<>();
    @InjectParam
    int examId;
    @InjectParam
    int score;
    @BindView(R.id.tv_nums)
    TextView tvNums;
    @BindView(R.id.tv_score)
    TextView tvScore;
    UserEntity user;
    ExamErrDetailEntity resultData;
    @Override
    protected void init() {
        RxEventProcessor.get().bind(this);
        ExamErrorRecordActivity__JumpCenter.bind(this);
        user = UserInfo.getUserInfo();
        tvScore.setText("得分 : "+String.valueOf(score));
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, SPAN_COUNT);
        adapter = new MyAdapter(subjectBeans);
        recycerView.setAdapter(adapter);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return subjectBeans.get(position).getItemType() == ExamErrDetailEntity.SubjectBean.TYPE_HEAD ? SPAN_COUNT : 1;
            }
        });
        recycerView.setLayoutManager(gridLayoutManager);
        HttpHeper.get().create(ExamService.class)
                .getErrInfo(examId,UserInfo.getUserInfo().getCpId())
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(getThread())
                .subscribe(new BaseCallBack<ExamErrDetailEntity>() {
                    @Override
                    public void onCallBackSuccess(ExamErrDetailEntity data) {
                        resultData = data;
                        if (data.getErrList() != null && data.getErrList().size() != 0) {
                            subjectBeans.add(new ExamErrDetailEntity.SubjectBean("错题汇总"));
                            subjectBeans.addAll(data.getErrList());
                        }
                        subjectBeans.add(new ExamErrDetailEntity.SubjectBean("所有题目"));
                        subjectBeans.addAll(data.getAllList());
                        tvNums.setText(String.valueOf(data.getAllList().size()));
                        adapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFail(String mes) {
                        showToast(mes);
                    }
                });
    }

    @Recipient(tag = "itemClickCall")
    public void itemClickCall(Object item){
        ExamErrDetailEntity.SubjectBean clickData = (ExamErrDetailEntity.SubjectBean)item;
        HttpHeper.get().create(ExamService.class)
                .getExamInfos(String.valueOf(examId),user.getName(), user.getIdCard(),user.getCpId())
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(getThread())
                .subscribe(new BaseCallBack<ExamInfosEntity>(this) {
                    @Override
                    public void onCallBackSuccess(ExamInfosEntity data) {
                        ExamInfosEntity result = getResult(clickData, data);
                        Gson json = new Gson();
                        Intent intent = new Intent();
                        intent.putExtra("ExamInfosEntity", json.toJson(result));
                        intent.putExtra("ExamId", String.valueOf(examId));
                        intent.putExtra("SaveQu", json.toJson(resultData.getAllList()) );
                        intent.setClass(ExamErrorRecordActivity.this, ExamDoActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onFail(String mes) {
                        showToast(mes);
                    }
                });
    }


    private ExamInfosEntity getResult( ExamErrDetailEntity.SubjectBean item, ExamInfosEntity data){
        List<ExamErrDetailEntity.SubjectBean>  list = resultData.getErrList();
        if(item.isErrorList()){
            //取出错误的题目
            List<ExamSubjectEntity> infoList = data.getList();
            List<ExamSubjectEntity> result = new ArrayList<ExamSubjectEntity>();
            for(ExamSubjectEntity info : infoList ){
                for(ExamErrDetailEntity.SubjectBean error : list){
                    if(info.getId() == error.getQueId()){
                        result.add(info);
                        break;
                    }
                }
            }
            data.setList(result);
            return data;
        }
        return  data;
    }


    public class MyAdapter extends BaseMultiItemQuickAdapter<ExamErrDetailEntity.SubjectBean, BaseViewHolder> {

        /**
         * Same as QuickAdapter#QuickAdapter(Context,int) but with
         * some initialization data.
         *
         * @param data A new list is created out of this one to avoid mutable list
         */
        public MyAdapter(List<ExamErrDetailEntity.SubjectBean> data) {
            super(data);
            addItemType(ExamErrDetailEntity.SubjectBean.TYPE_ITEN, R.layout.item_err_exam);
            addItemType(ExamErrDetailEntity.SubjectBean.TYPE_HEAD, R.layout.item_err_exam_head);

        }

        @Override
        protected void convert(BaseViewHolder helper, ExamErrDetailEntity.SubjectBean item) {
            switch (helper.getItemViewType()) {
                case ExamErrDetailEntity.SubjectBean.TYPE_HEAD:
                    helper.setText(R.id.tv_name, item.getHeadName());
                    break;
                case ExamErrDetailEntity.SubjectBean.TYPE_ITEN:
                    RelativeLayout rl =  (RelativeLayout)helper.getView(R.id.item);
                    helper.setText(R.id.tv_tihao, String.valueOf(item.getSort()));
                    helper.setText(R.id.tv_anser, item.getAnswer());
                    helper.setTextColor(R.id.tv_anser, item.isFlag() ? Color.parseColor("#333333") : Color.RED);
                    rl.setOnClickListener(new View.OnClickListener(){
                        @Override
                        public void onClick(View v) {
                            RxEventProcessor.get().post("itemClickCall",item);
                        }
                    });
                    break;
            }
        }
    }
    @Override
    protected void removeEvent(){
        RxEventProcessor.get().unBind(this);
    }

}
